//
//  ViewController.m
//  runtime获取变量
//
//  Created by webplus on 17/8/30.
//  Copyright © 2017年 sanyi. All rights reserved.
//

#import "ViewController.h"
#import <objc/runtime.h>
@interface ViewController ()
{
    NSString *_name;
    NSString *_sex;
}
@property (nonatomic,strong) NSString *age;
@property (nonatomic,strong) NSString *birthDay;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   NSLog(@"%@",[self getPropertieNamesByObject:self]) ;
    NSLog(@"%@",[self getVariableNamesByObject:self]) ;
    
}
//获取实例变量方法
- (void)getMethodListNamesByObject:(id)object{
    unsigned int methodCount;
    Method *methodList = class_copyMethodList([object class], &methodCount);
    unsigned int i = 0;
    for (; i < methodCount; i++) {
        Method method = methodList[i];
        NSLog(@"%@ ",  [NSString stringWithCString:sel_getName(method_getName(method)) encoding:NSUTF8StringEncoding]);
    }
    
    free(methodList);
}


//获取类的所有属性名
- (NSArray*)getPropertieNamesByObject:(id)object
{
    
    unsigned int outCount, i;
    
    // 获取注册类的属性列表，第一个参数是类，第二个参数是接收类属性数目的变量
    objc_property_t *properties = class_copyPropertyList([object class], &outCount);
    //定义一个数组来接收获取的属性名
    NSMutableArray *nameArray = [[NSMutableArray alloc] initWithCapacity:outCount];
    for (i = 0; i < outCount; i++) {
        //通过循环来获取单个属性
        objc_property_t property = properties[i];
        //取得属性名
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        //将得到的属性名放入数组中
        [nameArray addObject:propertyName];
        
    }
    free(properties);
    return nameArray;
}
//获取类的成员变量名
- (NSArray *)getVariableNamesByObject:(id)object
{
    unsigned int numIvars = 0;
    //获取类的所有成员变量
    Ivar * ivars = class_copyIvarList([object class], &numIvars);
    //定义一个数组来接收获取的属性名
    NSMutableArray *nameArray = [[NSMutableArray alloc] initWithCapacity:numIvars];
    for(int i = 0; i < numIvars; i++) {
        //得到单个的成员变量
        Ivar thisIvar = ivars[i];
        //得到这个成员变量的类型
        const char *type = ivar_getTypeEncoding(thisIvar);
        NSString *stringType =  [NSString stringWithCString:type encoding:NSUTF8StringEncoding];
        //此处判断非object-c类型时跳过
        if (![stringType hasPrefix:@"@"]) {
            continue;
        }
        //得到成员变量名
        NSString *variableName = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
        [nameArray addObject:variableName];
        
        //这个函数可以得到成员变量的值
        //object_getIvar(object, thisIvar)
        
    }
    free(ivars);
    return nameArray;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
